//
//  HJMainController.m
//  KaiChat
//
//  Created by lx on 2023/10/16.
//

#import "HJMainController.h"
#import "HJMainController.h"
#import "HJNavigationController.h"
#import "HJIM.h"
#import "HJConversationController.h"
#import "HJJsonAnimationView.h"

@interface HJMainController ()<UITabBarControllerDelegate>

@property (strong, nonatomic) NSArray *tabItemConfigurations;
@property (nonatomic, strong) NSDate *lastDate;
@property (nonatomic, assign) NSInteger lastClickIndex;
@property (nonatomic, weak) UIView *lastAnimationView;


@end

@implementation HJMainController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.delegate = self;
    
    [self setingTabBar];
    [self addChildViewController];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleMessageBadgeChangeNotification:) name:messageBadgeChangeNotification object:nil];
    [HJIM.shareIM.conversationManager updateBadge];
}

- (void)setingTabBar {
    
    self.tabBar.barTintColor = UIColor.whiteColor;
    self.tabBar.backgroundColor = UIColor.whiteColor;
    self.tabBar.translucent = NO;
    
    self.tabBar.layer.shadowColor = [UIColor.blackColor colorWithAlphaComponent:0.2].CGColor;
    self.tabBar.layer.shadowOffset = CGSizeMake(0, 0);
    self.tabBar.layer.shadowRadius = 2;
    self.tabBar.layer.shadowOpacity = 0.2;
    
    if (@available(iOS 13.0, *)) {
        [[UITabBar appearance] setTintColor:UIColor.tj_tabbarSelectColor];
        [[UITabBar appearance] setUnselectedItemTintColor:UIColor.tj_tabbarUnSelectColor];
        //        [UITabBar appearance].shadowImage = [UIImage new];
        [UITabBar appearance].backgroundImage = [UIImage imageWithColor:UIColor.clearColor];
        
        [[UITabBarItem appearance] setTitleTextAttributes:@{
            NSFontAttributeName:UIFontMake(12),
            NSForegroundColorAttributeName:UIColor.tj_tabbarUnSelectColor} forState:UIControlStateNormal];
        [[UITabBarItem appearance] setTitleTextAttributes:@{
            NSFontAttributeName:UIFontMake(12),
            NSForegroundColorAttributeName:UIColor.tj_tabbarSelectColor} forState:UIControlStateSelected];
    } else {
        //        self.tabBar.shadowImage = [UIImage new];
        [[UITabBarItem appearance] setTitleTextAttributes:@{
            NSFontAttributeName:UIFontMake(12),
            NSForegroundColorAttributeName:UIColor.tj_tabbarUnSelectColor} forState:UIControlStateNormal];
        [[UITabBarItem appearance] setTitleTextAttributes:@{
            NSFontAttributeName:UIFontMake(12),
            NSForegroundColorAttributeName:UIColor.tj_tabbarSelectColor} forState:UIControlStateSelected];
    }
}

- (void)handleMessageBadgeChangeNotification:(NSNotification *)not {
    
    HJConversationController *conversationController = nil;
    for (UINavigationController *conversationNavController in self.childViewControllers) {
        if ([conversationNavController.viewControllers.firstObject isKindOfClass: HJConversationController.class]) {
            conversationController = conversationNavController.viewControllers.firstObject;
            break;
        }
    }
    if (!conversationController) return;
    
    NSInteger badgeValue = [not.object intValue];
    if (badgeValue > 0) {
        if (badgeValue > 99) {
            conversationController.tabBarItem.badgeValue = @"99+";
            UIApplication.sharedApplication.applicationIconBadgeNumber = 99;
            //            [JPUSHService setBadge:99];
        } else {
            UIApplication.sharedApplication.applicationIconBadgeNumber = badgeValue;
            conversationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld", badgeValue];
            //            [JPUSHService setBadge:badgeValue];
        }
    } else {
        NSDate *currentDate = [NSDate date];
        if (!_lastDate || [currentDate timeIntervalSinceDate:_lastDate] >= 2) {
            if (UIApplication.sharedApplication.applicationIconBadgeNumber > 0 && badgeValue == 0) {
                //                [[TJIMSDK shareSDK].userManager readMessageWithType:@"" sessionId:nil completion:^(NSError * _Nullable error) {}];
            }
            _lastDate = currentDate;
        }
        conversationController.tabBarItem.badgeValue = nil;
        UIApplication.sharedApplication.applicationIconBadgeNumber = 0;
        //        [JPUSHService setBadge:0];
    }
}


- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    
    
    [self setAnaimationWithTabBarController:tabBarController selectViewController:viewController];
}

- (void)setAnaimationWithTabBarController:(UITabBarController *)tabBarController selectViewController:(UIViewController *)viewController {
    
    NSInteger index = [tabBarController.viewControllers indexOfObject:viewController];
    if (_lastClickIndex == index) {//取消上一个的
        return;
    }
    
    if (self.lastAnimationView) {
        self.lastAnimationView.hidden = NO;
        HJJsonAnimationView *lottieAnimationView = [self.lastAnimationView.superview viewWithTag:11111];
        if (lottieAnimationView) {
            [lottieAnimationView stop];
            [lottieAnimationView removeFromSuperview];
            lottieAnimationView = nil;
        }
    }
    
    NSMutableArray <UIView *>*tabBarSwappableImageViews = [NSMutableArray arrayWithCapacity:4];
    _lastClickIndex = index;
    
    for (UIView *tempView in tabBarController.tabBar.subviews) {
        if ([tempView isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            for (UIImageView *tempImageView in tempView.subviews) {
                if ([tempImageView isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
                    [tabBarSwappableImageViews addObject:tempImageView];
                }
            }
        }
    }
    
    UIView *currentAnimationView = tabBarSwappableImageViews[index];
    _lastAnimationView = currentAnimationView;
    
    NSDictionary *dict = self.tabItemConfigurations[index];
    
    __block HJJsonAnimationView *lottieAnimationView = [[HJJsonAnimationView alloc] initWithName:dict[@"jsonName"]];
    lottieAnimationView.frame = currentAnimationView.bounds;
    lottieAnimationView.center = currentAnimationView.center;
    lottieAnimationView.tag = 11111;
    [currentAnimationView.superview addSubview:lottieAnimationView];
    currentAnimationView.hidden = YES;
    [lottieAnimationView playComplete:^(BOOL res) {
        if (res) {
            currentAnimationView.hidden = NO;
            [lottieAnimationView removeFromSuperview];
            lottieAnimationView = nil;
        }
    }];
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
//    
//    CGRect frame = self.tabBar.frame;
//    frame.size.height = TabBarHeight;
//    frame.origin.y = self.view.frame.size.height - TabBarHeight;
//    self.tabBar.frame = frame;
    
    
    //    for (UIView *subView in self.tabBar.subviews) {
    //        if (![subView isKindOfClass:GJTabBar.class]) {
    //            [subView removeFromSuperview];
    //        }
    //    }
    //    self.gj_tabbar.frame = CGRectMake(0, 0, self.tabBar.tj_width, self.tabBar.tj_height);
}


- (void)addChildViewController {
    [self.tabItemConfigurations enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self addChildViewController:[[NSClassFromString(obj[@"controllerName"]) alloc] init] image:obj[@"iconName"]  selectImage:obj[@"selectIconName"] title:obj[@"title"]];
    }];
}

- (void)addChildViewController:(UIViewController *)childController image:(NSString *)image  selectImage:(NSString *)selectImage title:(NSString *)title {
    
    HJNavigationController *navigationController = [[HJNavigationController alloc] initWithRootViewController: childController];
    navigationController.view.backgroundColor = [UIColor whiteColor];
    [self addChildViewController: navigationController];
    childController.title = title;
    childController.navigationItem.title = title;
    childController.tabBarItem.image = [UIImage imageNamed:image];
    childController.tabBarItem.selectedImage = [UIImage imageNamed:selectImage];
}

- (NSArray *)tabItemConfigurations {
    if (!_tabItemConfigurations) {
        _tabItemConfigurations = @[
            @{
                @"controllerName": @"HJConversationController",
                @"iconName": @"chat",
                @"selectIconName": @"chat_select_icon",
                @"title": @"Chats",
                @"jsonName": @"chats"
            },
            //            @{
            //                @"controllerName": @"HJWalletController",
            //                @"iconName": @"community",
            //                @"selectIconName": @"community_select_icon",
            //                @"title": @"Community"
            //            },
            //            @{
            //                @"controllerName": @"HJWalletController",
            //                @"iconName": @"circle",
            //                @"selectIconName": @"circle_select_icon",
            //                @"title": @"Circle"
            //            },
            @{
                @"controllerName": @"HJWalletController",
                @"iconName": @"wallet",
                @"selectIconName": @"wallet_select_icon",
                @"title": @"Wallet",
                @"jsonName": @"wallet"
            }
        ];
    }
    return _tabItemConfigurations;
}


@end
